package org.example.auth.controller;

import org.example.auth.contract.request.RoleRequestForQuery;
import org.example.auth.contract.request.RoleRequestForSave;
import org.example.auth.contract.request.RoleRequestForUserBind;
import org.example.auth.contract.response.RoleResponse;
import org.example.auth.contract.response.RoleResponseForUser;
import org.example.auth.convert.RoleConvert;
import org.example.auth.model.entity.Role;
import org.example.auth.service.RoleService;
import org.example.auth.service.UserRoleService;
import org.example.misc.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleConvert roleConvert;

    /**
     * 保存角色
     */
    @PostMapping("/save")
    Result<RoleResponse> save(@RequestBody @Validated RoleRequestForSave request) {
        return Result.ok(roleConvert.clone(roleService.save(request)));
    }

    /**
     * 删除角色
     */
    @GetMapping("deleteRole")
    Result<Boolean> deleteRole(@RequestParam Long id) {
        roleService.deleteRole(id);
        return Result.ok(Boolean.TRUE);
    }

    /**
     * 获取角色列表
     */
    @PostMapping("getRoles")
    Result<List<RoleResponse>> getRoles(@RequestBody RoleRequestForQuery request) {
        List<Role> roleList = roleService.getRoles(request);
        return Result.ok(roleConvert.clone(roleList));
    }

    /**
     * 获取 用户相关的角色
     */
    @GetMapping("groupRolesForUser")
    Result<RoleResponseForUser> groupRolesForUser(@RequestParam Long userId) {
        return Result.ok(roleService.groupRolesForUser(userId));
    }

    /**
     * 用户角色批量绑定
     */
    @PostMapping("/batchBindRoleForUser")
    Result<Boolean> batchBindRoleForUser(@RequestBody RoleRequestForUserBind request) {
        userRoleService.batchBindRoleForUser(request);
        return Result.ok(Boolean.TRUE);
    }

    /**
     * 用户角色单个绑定
     */
    @GetMapping("/bindRoleForUser")
    Result<Boolean> bindRoleForUser(@RequestParam Long userId, @RequestParam Long roleId) {
        userRoleService.bindRoleForUser(userId, roleId);
        return Result.ok(Boolean.TRUE);
    }

    /**
     * 用户角色单个解绑
     */
    @GetMapping("/unbindRoleForUser")
    Result<Boolean> unbindRoleForUser(@RequestParam Long userId, @RequestParam Long roleId) {
        userRoleService.unbindRoleForUser(userId, roleId);
        return Result.ok(Boolean.TRUE);
    }


}
